//
//  JTTYPGZLViewController.m
//  Estate
//
//  Created by houzhen on 2017/11/4.
//  Copyright © 2017年 ttsx. All rights reserved.
//

//时间cell
#import "TopTimeCell.h"
// 显示cell
#import "DefaineCell.h"
// 位置cell
#import "PositionTableCell.h"
// 单行输入cell
#import "QianDTableCell.h"
#import "PositionBlockModel.h"
#import "OrientationViewController.h"

#import "JJTYPZZLViewController.h"


@interface JJTYPZZLViewController ()<UITableViewDelegate,UITableViewDataSource>


@property (strong ,nonatomic)TPKeyboardAvoidingTableView *tableView;   /**表格*/
// block参数
@property (strong, nonatomic) PositionBlockModel *blockModel;
// 当前被点的地址数据模型
@property (strong, nonatomic) AddressModel *addressModel;

// 天气cell
@property (strong, nonatomic) DefaineCell *weatherCell;

@property(strong, nonatomic)NSMutableArray *weatherArr;


@end


@implementation JJTYPZZLViewController
{
    NSMutableArray* _titArr, *testArr;
}

// 表格
- (TPKeyboardAvoidingTableView *)tableView {
    if (_tableView==nil) {
        _tableView = [[TPKeyboardAvoidingTableView alloc] initWithFrame:CGRECTS(0, 0, 375, 555) style:UITableViewStylePlain];
        _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
        _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        _tableView.delegate=self;
        _tableView.dataSource=self;
        [_tableView registerClass:[PositionTableCell class] forCellReuseIdentifier:@"poCell"];
        [_tableView registerClass:[TopTimeCell class] forCellReuseIdentifier:@"toptime"];
        [_tableView registerNib:[UINib nibWithNibName:@"QianDTableCell" bundle:nil] forCellReuseIdentifier:@"qiandCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"DefaineCell" bundle:nil] forCellReuseIdentifier:@"deCell"];
        [LSUtility setExtraCellLineHidde:_tableView tabHeader:YES tabFooter:NO];
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    //添加底部视图
    [self.view addSubview:self.tableView];
    //天气地区
    self.weatherArr = [LSUtility getWeatherArea];
    
    [self setData];
    
    _titArr = [[NSMutableArray alloc]initWithObjects:@"旁站项目:",@"项目名称:",@"监理单位:",@"监理合同号:",@"施工单位:",@"施工合同号:",@"工程地点:",@"工序/部位(桩号):",@"编号:",@"所在地区:",@"天气:",nil];
    testArr = [LSUtility constructionUnitFromProId:PROID];
}
-(void)setData{
    
    if (!self.basicModel.weather) {
        //天气数组
        NSMutableArray *wArr=DEF_PERSISTENT_GET_OBJECT(@"WEATHER");
        NSString *areaStr=[self.weatherArr firstObject];
        NSString *weather=[[wArr firstObject]objectForKey:areaStr];
        self.basicModel.weather = [NSString stringWithFormat:@"%@/%@",areaStr,weather];
    }
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self.view endEditing:YES];
}

#pragma mark-UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section==0){
        return 1;
        
    }else{
        return _titArr.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section==0) {
        return 100*BIZ;
    }
    return 44;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    __weak typeof(self)weakSelf = self;
    //获得组数
    long section=indexPath.section;
    long row=indexPath.row;
    
    if(section==0){
        TopTimeCell *cell=[tableView dequeueReusableCellWithIdentifier:@"toptime" forIndexPath:indexPath];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.isEdit = self.isEdit;
        cell.beginLab.text=[LSUtility TimeNow];
        //结束时间加五分钟
        cell.endLab.text=[LSUtility nowTimeAdd5Sec];
//        self.basicModel.beginTime = cell.beginLab.text;
        
        if (self.basicModel.number != nil) {
            cell.beginLab.text = self.basicModel.beginTime;
            cell.endLab.text = self.basicModel.endTime;
            
            self.basicModel.beginTime = cell.beginLab.text;
            self.basicModel.endTime = cell.endLab.text;
            
        } else {
            self.basicModel.beginTime = cell.beginLab.text;
            self.basicModel.endTime = cell.endLab.text;
        }
        
        cell.clickTimeBlock=^(NSString *value) {
            self.basicModel.beginTime = value;
        };
        cell.clickTimeBlock_end=^(NSString *value) {
            self.basicModel.endTime = value;
        };
        return cell;
        
    }else {
        if (row==0) {
            QianDTableCell *cell=[tableView dequeueReusableCellWithIdentifier:@"qiandCell" forIndexPath:indexPath];
            cell.title.text = _titArr[indexPath.row];
            
            if ([self.isSubStr isEqualToString:@"RECORD_02_JJ_01"]) {
                cell.isedit = self.isEdit;
                cell.textField.placeholder = @"请输入旁站项目名称";
                if (self.basicModel.siteName) {
                    cell.textField.text = self.basicModel.siteName;
                }
                cell.textValueChangedBlock = ^(NSString *valueStr) {
                    self.basicModel.siteName = valueStr;
                };
            } else {
                cell.isedit = NO;
                if ([self.isSubStr isEqualToString:@"RECORD_02_JJ_02"]) {
                    self.basicModel.siteName = @"桩基钢筋笼安放";
                    
                } else if ([self.isSubStr isEqualToString:@"RECORD_02_JJ_03"]) {
                    self.basicModel.siteName = @"灌注桩首盘砼浇筑";
                    
                } else if ([self.isSubStr isEqualToString:@"RECORD_02_JJ_04"]) {
                    self.basicModel.siteName = @"路面(沥青)混凝土摊铺";
                    
                } else if ([self.isSubStr isEqualToString:@"RECORD_02_JJ_05"]) {
                    self.basicModel.siteName = @"预应力张拉";
                    
                } else if ([self.isSubStr isEqualToString:@"RECORD_02_JJ_06"]) {
                    self.basicModel.siteName = @"预应力压浆";
                }
                cell.textField.text = self.basicModel.siteName;
            }
            return cell;
            
        }else if (row==1) {//项目名称
            // 显示cell
            DefaineCell *cell=[tableView dequeueReusableCellWithIdentifier:@"deCell" forIndexPath:indexPath];
            cell.title.text = _titArr[indexPath.row];
            if (!self.basicModel.proName) {
                self.basicModel.proName = DEF_PERSISTENT_GET_OBJECT(@"proname");
            }
            cell.text.text = self.basicModel.proName;
            return cell;
            
        }else if(row==2){//监理单位
            DefaineCell *cell=[tableView dequeueReusableCellWithIdentifier:@"deCell" forIndexPath:indexPath];
            cell.title.text = _titArr[indexPath.row];
            
            if (self.basicModel.jianliDanweiID) {
                cell.text.text = self.basicModel.jianliDanwei;
                
            } else {
                // 查找监理单位
                NSString *sqlStr = [NSString stringWithFormat:@"SELECT ID, PRO_UNIT_NAME FROM PROJECT_UNIT WHERE PRO_ID = '%@' AND PRO_UNIT_TYPE = 'UNIT_00'", DEF_PERSISTENT_GET_OBJECT(@"proid")];
                FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
                [db open];
                FMResultSet *result = [db executeQuery:sqlStr];
                while ([result next]) {
                    // 单位名称
                    NSString *proName = [result stringForColumn:@"PRO_UNIT_NAME"];
                    cell.text.text = proName;
                    self.basicModel.jianliDanwei = proName;
                    // 单位ID
                    NSString *supervisorProUnitId = [result stringForColumn:@"ID"];
                    self.basicModel.jianliDanweiID = supervisorProUnitId;
                }
                [db close];
            }
            return cell;
            
        }else if(row==3){//监理合同号
            DefaineCell *cell=[tableView dequeueReusableCellWithIdentifier:@"deCell" forIndexPath:indexPath];
            cell.title.text = _titArr[indexPath.row];
            
            if (self.basicModel.contrctNumber) {
                cell.text.text = self.basicModel.contrctNumber;
                
            } else {
                // 查找监理合同段
                NSString *sqlStr = [NSString stringWithFormat:@"SELECT CONTRCT_NUMBER FROM PROJECT_UNIT WHERE PRO_ID = '%@' AND PRO_UNIT_TYPE = 'UNIT_00'", DEF_PERSISTENT_GET_OBJECT(@"proid")];
                FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
                [db open];
                FMResultSet *result = [db executeQuery:sqlStr];
                while ([result next]) {
                    NSString *contrctNumber = [result stringForColumn:@"CONTRCT_NUMBER"];
                    cell.text.text = contrctNumber;
                    // 记录监理合同段
                    self.basicModel.contrctNumber = contrctNumber;
                }
                [db close];
            }
            return cell;
            
        }else if(row==4){//施工单位 可点击选择
            DefaineCell *cell=[tableView dequeueReusableCellWithIdentifier:@"deCell" forIndexPath:indexPath];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.title.text = _titArr[indexPath.row];
            cell.text.text = self.basicModel.shigongDanwei ? self.basicModel.shigongDanwei : @"请选择";
            return cell;
            
        }else if(row==5){//施工合同号
            DefaineCell *segmentCell = [tableView dequeueReusableCellWithIdentifier:@"deCell" forIndexPath:indexPath];
            segmentCell.title.text = _titArr[indexPath.row];
            segmentCell.text.text = self.basicModel.constructionNumber;
            return segmentCell;
            
        }else if(row==6) {//工程地点
            PositionTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"poCell" forIndexPath:indexPath];
            cell.title.text = _titArr[indexPath.row];
            cell.isEdit=self.isEdit;
            if (self.basicModel.location == nil || [self.basicModel.location isEqualToString:@""]) {
                cell.btnStr = @"请选择位置";
            } else {
                NSDictionary *dic = [LSUtility dictionaryWithJsonString:self.basicModel.location];
                cell.btnStr = [NSString stringWithFormat:@"%@ %@",dic[@"address"],dic[@"leftDistanceStr"]];
            }
            
            cell.cliclWzBlock = ^{
                OrientationViewController *location=[[OrientationViewController alloc]init];
                location.flagStr = @"jilu";
                location.dataArr1 = [NSMutableArray arrayWithArray:self.blockModel.dataArr1];
                location.dataArr2 = [NSMutableArray arrayWithArray:self.blockModel.dataArr2];
                location.dataArr3 = [NSMutableArray arrayWithArray:self.blockModel.dataArr3];
                location.dataArr4 = [NSMutableArray arrayWithArray:self.blockModel.dataArr4];
                location.aID = self.blockModel.aID;
                location.firstID = self.blockModel.firstID;
                location.secondID = self.blockModel.secondID;
                location.thirdID = self.blockModel.thirdID;
                
                location.keyStr = self.blockModel.keyStr;
                location.number = self.blockModel.number;
                location.addressArr = [NSMutableArray arrayWithArray:self.blockModel.addressArr];
                location.position = self.blockModel.position;
                location.addressModel = self.addressModel;
                location.selectedX = self.blockModel.selectedX;
                location.selectedY = self.blockModel.selectedY;
                location.scale = self.blockModel.scale;
                
                if (location.number) {
                    location.hC = YES;
                }
                [self.navigationController pushViewController:location animated:YES];
                // 回传位置值
                location.returnPlaceInfoBlock = ^(PositionBlockModel *model, AddressModel *addModel, NSString *addInfoStr){
                    self.blockModel = model;
                    self.addressModel = addModel;
                    self.basicModel.locationInfo = model.keyStr;
                    self.basicModel.locationId = model.aID;
                    self.basicModel.location = addInfoStr;
                    
                    [weakSelf.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:6 inSection:1]] withRowAnimation:UITableViewRowAnimationFade];
                };
            };
            return cell;
        }else if(row==7){//工序/部位(桩号)
            QianDTableCell *cell=[tableView dequeueReusableCellWithIdentifier:@"qiandCell" forIndexPath:indexPath];
            cell.isedit = self.isEdit;
            
            cell.title.text = _titArr[indexPath.row];
            cell.textField.placeholder = @"请输入工序/部位(桩号)";
            if (self.basicModel.otherAddress) {
                cell.textField.text = self.basicModel.otherAddress;
            }
            cell.textValueChangedBlock = ^(NSString *str) {
                self.basicModel.otherAddress = str;
            };
            return cell;
            
        }else if(row==8){//编号
            QianDTableCell *cell=[tableView dequeueReusableCellWithIdentifier:@"qiandCell" forIndexPath:indexPath];
            cell.isedit = self.isEdit;
            cell.title.text = _titArr[indexPath.row];
            cell.textField.placeholder = @"请输入编号";
            if(self.basicModel.number){
                cell.textField.text = self.basicModel.number;
            }
            cell.textValueChangedBlock = ^(NSString *str) {
                self.basicModel.number = str;
            };
            return cell;
            
        } else if(row==9) {//所在地区 可点击选择
            DefaineCell *cell=[tableView dequeueReusableCellWithIdentifier:@"deCell" forIndexPath:indexPath];
            cell.title.text = _titArr[indexPath.row];
            if (self.basicModel.weather && ![self.basicModel.weather isEqualToString:@""]) {
                NSRange range = [self.basicModel.weather rangeOfString:@"/"];
                if (range.length > 0) {
                    NSString *posStr = [self.basicModel.weather substringToIndex:range.location];
                    cell.text.text = posStr;
                }
            }else{
                cell.text.text = @"请选择";
            }
            return cell;
            
        }else{//天气
            self.weatherCell=[tableView dequeueReusableCellWithIdentifier:@"deCell" forIndexPath:indexPath];
            self.weatherCell.title.text = _titArr[indexPath.row];
            
            NSRange range = [self.basicModel.weather rangeOfString:@"/"];
            NSString *posStr;
            if (range.length) {
                posStr = [self.basicModel.weather substringFromIndex:range.location+1];
                self.weatherCell.text.text = posStr;
            }
            return self.weatherCell;
        }
    }
}

#pragma MARK - didSelectRowAtIndexPath(选择信息)
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    
    if (self.isEdit && section == 1) {
        // 选择施工单位
        if (row == 4) {
            // 查找施工单位列表
            NSArray *constructionUnitArr = [self getConstructionUnitList];
            if (constructionUnitArr.count > 0) {
                NSMutableArray *arr = [NSMutableArray array];
                NSNumber *ninit = [NSNumber numberWithInteger:0];
                for (NSDictionary *dic in constructionUnitArr) {
                    [arr addObject:dic[@"NAME"]];
                }
                [ActionSheetStringPicker showPickerWithTitle:nil rows:@[arr] initialSelection:@[ninit] doneBlock:^(ActionSheetStringPicker *picker, NSArray *selectedIndex, NSArray *selectedValue) {
                    
                    // 修改数据
                    DefaineCell *cell = [tableView cellForRowAtIndexPath:indexPath];
                    cell.text.text = [selectedValue firstObject];
                    NSInteger index = [[selectedIndex firstObject] integerValue];
                    NSDictionary *constructionUnitDic = constructionUnitArr[index];
                    // 查找施工合同段
                    [self checkConstruction:constructionUnitDic[@"ID"]];
                    
                    // 施工单位信息
                    self.basicModel.shigongDanwei = constructionUnitDic[@"NAME"];
                    self.basicModel.shigongDanweiID = constructionUnitDic[@"ID"];
                    
                    // 查找人员信息
                    if (constructionUnitDic[@"ID"] && ![constructionUnitDic[@"ID"] isEqualToString:@""]) {
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshPeople" object:constructionUnitDic[@"ID"]];
                    }
                } cancelBlock:nil origin:self.view];
                
            } else {
                [LSUtility showToastWithMessage:@"数据为空" inView:self.view Andtime:1.0];
            }
            
            // 选择地区
        } else if (row == 9) {
            NSNumber *ninit = [NSNumber numberWithInteger:0];
            
            NSMutableArray *wArr=DEF_PERSISTENT_GET_OBJECT(@"WEATHER");
            if(!wArr){
                wArr=[NSMutableArray arrayWithObject:@{@"无":@"暂时无法获得天气信息"}];
            }
            if(self.weatherArr.count<1){
                [self.weatherArr addObject:@"无"];
            }
            [ActionSheetStringPicker showPickerWithTitle:nil rows:@[self.weatherArr] initialSelection:@[ninit] doneBlock:^(ActionSheetStringPicker *picker, NSArray * selectedIndex, NSArray *selectedValue) {
                int iv = [(NSNumber*)[selectedIndex firstObject] intValue];
                NSDictionary *weadic=wArr[iv];
                NSString *address =self.weatherArr[iv];
                self.basicModel.weather=[NSString stringWithFormat:@"%@/%@",address,weadic[address]];
                //刷新城市、刷新天气
                [self.tableView reloadData];
                
            } cancelBlock:nil origin:self.view];
            
        }
        
    }
}

// 查找施工单位列表
- (NSArray *)getConstructionUnitList {
    NSString *sqlStr = [NSString stringWithFormat:@"SELECT ID, PRO_UNIT_NAME FROM PROJECT_UNIT WHERE PRO_ID = '%@' AND PRO_UNIT_TYPE = 'UNIT_02'", DEF_PERSISTENT_GET_OBJECT(@"proid")];
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    NSMutableArray *constructionUnitArr = [NSMutableArray array];
    FMResultSet *result = [db executeQuery:sqlStr];
    while ([result next]) {
        NSMutableDictionary *mDic = [NSMutableDictionary dictionary];
        NSString *idStr = [result stringForColumn:@"ID"];
        NSString *proName = [result stringForColumn:@"PRO_UNIT_NAME"];
        [mDic setObject:idStr forKey:@"ID"];
        [mDic setObject:proName forKey:@"NAME"];
        [constructionUnitArr addObject:mDic];
    }
    [db close];
    return constructionUnitArr;
}

// 查找施工合同段及合同金额
- (void)checkConstruction:(NSString *)idStr {
    NSString *sqlStr = [NSString stringWithFormat:@"SELECT CONTRCT_NUMBER FROM PROJECT_UNIT WHERE ID = '%@'", idStr];
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    FMResultSet *result = [db executeQuery:sqlStr];
    while ([result next]) {
        NSString *contrctNumber = [result stringForColumn:@"CONTRCT_NUMBER"];
        // 保存信息
        self.basicModel.constructionNumber = contrctNumber;
        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:5 inSection:1]] withRowAnimation:UITableViewRowAnimationFade];
    }
    [db close];
}


// 点击屏幕结束编辑
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}


@end

